package com.michael.demos.base.design.observer.newspaper;

import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 类功能描述:
 * <pre>
 *   报社
 * </pre>
 *
 * @author Michael
 * @version 1.0
 * @date 2020/8/24 16:37
 */
public class NewsOffice implements Provider {

    private static final long DELAY = 2 * 1000;

    private final List<Consumer> users = new LinkedList<>();

    public NewsOffice() {
        generateNews();
    }

    /**
     * 模拟产生新闻，每个2s发送一次
     */
    private void generateNews() {
        System.out.println("报社准备发放报纸");
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            int titleCount = 1;
            int contentCount = 1;

            @Override
            public void run() {
                send(new News("title:" + titleCount++, "content:" + contentCount++));
            }
        }, DELAY, 2000);
    }

    @Override
    public void register(Consumer consumer) {
        if (consumer == null) {
            return;
        }
        synchronized (users) {
            if (!users.contains(consumer)) {
                users.add(consumer);
            }
        }
    }

    @Override
    public void remove(Consumer consumer) {
        users.remove(consumer);
    }

    @Override
    public void send(News model) {
        for (Consumer user : users) {
            user.receive(model);
        }
    }
}
